package com.shangyueshang.security;

import com.shangyueshang.enums.UserStatus;
import com.shangyueshang.model.SysUser;
import com.shangyueshang.service.SysUserService;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author: JokeyZheng
 * @email: zhengjingfeng@ruqimobility.com
 * @created: 2022/1/6 18:31
 * @version: v1.0.0
 */
@Service
public class UserDetailServiceImpl implements UserDetailsService {
	
	@Resource
	private SysUserService sysUserService;
	
	@Override
	public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
		SysUser sysUser = sysUserService.findByName(username);
		if (Objects.isNull(sysUser)) {
			throw new UsernameNotFoundException("账号或密码错误");
		}
		
		// 用户权限列表，根据用户拥有的权限标识与如 @PreAuthorize("hasAuthority('sys:menu:view')") 标注的接口对比，决定是否可以调用接口
		Set<String> permissions = sysUserService.findPermissions(username);
		List<GrantedAuthority> grantedAuthorities = permissions.stream().map(GrantedAuthorityImpl::new).collect(Collectors.toList());
		return new JwtUserDetails(
				username,
				sysUser.getPassword(),
				sysUser.getSalt(),
				UserStatus.of(sysUser.getStatus()),
				grantedAuthorities,
				sysUser.getAuthorizedShops()
		);
	}
}
